<template>
	<div ref="divRef" :style="{height:height+'px'}" />
</template>

<script>
	import {
		AiEditor
	} from "aieditor";
	import "aieditor/dist/style.css"

	export default {
		name: "gz-editor",
		components: {},
		emits: ['update:modelValue'],
		props: {
			modelValue: {
				type: [String],
				default () {
					return "";
				},
			},
			height: {
				type: Number,
				default: 350
			},
			rootPath: {
				type: String,
				default: "aiEditor",
				required: true
			},
		},
		data() {
			return {
				aiEditor: null
			};
		},
		mounted() {
			this.initData(this.modelValue)
		},
		methods: {
			initData(content){
				this.aiEditor = new AiEditor({
					element: this.$refs.divRef,
					contentRetention: false,
					draggable: true,
					pasteAsText: false,
					ai: {
						models: {
							spark: {
								appId: "b1e1f665",
								apiKey: "53e258c6afac31bacd017b2079c089e9",
								apiSecret: "Mzk5NzQxOWNhMjE2NTMxY2Y4ZWFjODFh",
								protocol: "wss", //或者 wss
								version: "v4.0", //或者其他
							}
						}
					},
					placeholder: "点击输入内容...",
					content: content,
					onChange: (aiEditor) => {
						// 监听到用编辑器内容发生变化了，控制台打印编辑器的 html 内容...
						console.log(aiEditor.getHtml())
						this.$emit('update:modelValue', aiEditor.getHtml())
					},
					image: {
						allowBase64: true,
						defaultSize: 350,
						uploadFormName: "file", //上传时的文件表单名称
						// customMenuInvoke
						uploadUrl: this.$http.upFileUrl + "?rootPath=" + this.rootPath,
						uploadHeaders: this.$http.uploadHeaders(),
						uploaderEvent: {
							onUploadBefore: (file, uploadUrl, headers) => {
								//监听图片上传之前，此方法可以不用回任何内容，但若返回 false，则终止上传
							},
							onSuccess: (file, response) => {
								//监听图片上传成功
								//注意：
								// 1、如果此方法返回 false，则图片不会被插入到编辑器
								// 2、可以在这里返回一个新的 json 给编辑器
								let data = response.result
								data.src = data.url
								data.alt = data.name
								console.info(data)
								return {
									errorCode: 0,
									data: data
								}
							},
							onFailed: (file, response) => {
								//监听图片上传失败，或者返回的 json 信息不正确
							},
							onError: (file, error) => {
								//监听图片上传错误，比如网络超时等
							},
						},
						//不知道为什么一直无法成功
						// uploader: (mfile, uploadUrl, headers, formName) => {
						// 	return new Promise((resolve, reject) => {
						// 		this.$api.upFile({
						// 			file: mfile,
						// 			rootPath: "jichukuangjia"
						// 		}).then(data => {
						// 			resolve(data)
						// 		}).catch(err => {
						// 			reject(error);
						// 		})
						// 	});
						// }
					}
				})
			}
		},
	};
</script>
<style scoped lang="scss">
</style>